package com.example.ktdemo.nav

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.viewpager.widget.ViewPager
import java.util.concurrent.atomic.AtomicInteger

/**
 * FileName: NavigationBottomView
 * Author: lzt
 * Date: 2022/5/10 15:02
 * 自定义底部导航栏控件
 */
class NavBottomView : LinearLayout, NavBottomApi {
    //头部ID
    private val INTEGER_ID_LL_CONTENT = 1
    private val INTEGER_ID_TV_NAME = 2
    private val INTEGER_ID_IV_IMG = 3
    private val INTEGER_ID_TV_UNREAD = 4

    //ui对象集合
    private var mUiInfoList: MutableList<NavBottomUIInfo> = ArrayList()

    //控件根目录集合
    private var mUIParentList: MutableList<RelativeLayout> = ArrayList()

    //当前选中的控件位置
    private var mSelPosition: AtomicInteger = AtomicInteger(-1)

    //监听
    private var mListener: NavBottomOnTabSelectListener? = null

    //关联的viewpager
    private var mRelViewPager: ViewPager? = null

    //动画开关标识
    private var mAnimImgSwitch = true
    private var mAnimTxtSwitch = false

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {
        orientation = HORIZONTAL
        gravity = Gravity.CENTER
    }

    //内部实现---------------------------------------------------------------------------------------


    private fun innerSetSelWithPosition(
        position: Int,
        updateViewPager: Boolean,
        smoothAnim: Boolean = true
    ) {
        val totalSize = getTabCount()
        if (totalSize == 0) {
            return
        }
        val oldSelPosition = mSelPosition.get()
        //如果已经选择了，则不执行
        if (oldSelPosition == position) {
            mListener?.reSelect(position)
            return
        }
        //旧按钮恢复
        setButtonUI(oldSelPosition, false)
        //新按钮设置
        setButtonUI(position, true)
        //判断是否需要设置view pager位置
        if (updateViewPager) {
            mRelViewPager?.setCurrentItem(position, smoothAnim)
        }
        mSelPosition.set(position)
    }


    //根据标识查询数据位置
    private fun queryPosWithIdentify(identify: Int): Int {
        if (mUIParentList.isNullOrEmpty()) {
            return -1
        }
        return mUiInfoList.indexOfFirst { it.identify == identify }
    }

    /**
     * 初始化点击事件
     * */
    private fun initParentClickEvent(parentLinear: LinearLayout, position: Int) {
        parentLinear.setOnClickListener {
            setSelWithPosition(position)
        }
    }

    /**
     * dp转px
     */
    private fun dip2px(dp: Int): Int {
        val density: Float = context.applicationContext.resources.displayMetrics.density
        return (density * dp + 0.5).toInt()
    }


    /**
     * 设置按钮状态--选中/未选中
     * */
    private fun setButtonUI(position: Int, select: Boolean) {
        val totalSize = getTabCount() - 1
        if (position != -1 && position <= totalSize) {
            val uiInfo = mUiInfoList[position]
            val idKey = uiInfo.identify
            val ivId = INTEGER_ID_IV_IMG + idKey
            val tvId = INTEGER_ID_TV_NAME + idKey
            val rootLinear = mUIParentList[position]
            val ivImg = rootLinear.findViewById<NavBottomAnimImageVIew>(ivId)
            val tvName = rootLinear.findViewById<NavBottomAnimTextVIew>(tvId)
            if (uiInfo.imgSel?.isRecycled == false && uiInfo.imgUnSel?.isRecycled == false) {
                ivImg?.setImageBitmap(if (select) uiInfo.imgSel else uiInfo.imgUnSel)
            }
            tvName?.text = if (select) uiInfo.nameSel ?: "" else uiInfo.nameUnSel ?: ""
            tvName?.setTextColor(if (select) uiInfo.nameSelColor else uiInfo.nameUnSelColor)
            if (select) {
                mListener?.select(position)
            } else {
                mListener?.unSelect(position)
            }
            ivImg.isSelected = select
            tvName.isSelected = select
            ivImg.showAnim(mAnimImgSwitch)
            tvName.showAnim(mAnimTxtSwitch)
        }
    }

    private fun innerInitUI(uiInfoList: MutableList<NavBottomUIInfo>?) {
        if (uiInfoList.isNullOrEmpty()) {
            return
        }
        mUIParentList.clear()
        mUiInfoList.clear()
        mUiInfoList.addAll(uiInfoList)
        removeAllViews()
        var childCounter = 0
        var parentCounter = 0
        //构建------------------------------
        mUiInfoList.forEach {
            //跟布局--relativelayout
            val rootRelativeLayout = RelativeLayout(context)
            addView(rootRelativeLayout)
            val rootParams = rootRelativeLayout.layoutParams as LinearLayout.LayoutParams
            rootParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
            rootParams.width = 0
            rootParams.weight = 1f
            rootRelativeLayout.layoutParams = rootParams
            mUIParentList.add(rootRelativeLayout)
            //内容布局--linearlayout imageview textview
            val parentLinear = LinearLayout(context)
            val KEY_ID = it.identify

            parentLinear.id = INTEGER_ID_LL_CONTENT + KEY_ID
            rootRelativeLayout.addView(parentLinear)
            val parentParams = parentLinear.layoutParams as RelativeLayout.LayoutParams
            parentParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT
            parentParams.width = RelativeLayout.LayoutParams.MATCH_PARENT
            parentLinear.layoutParams = parentParams

            parentLinear.orientation = LinearLayout.VERTICAL
            parentLinear.gravity = Gravity.CENTER

            //unread view
            rootRelativeLayout.postDelayed(Runnable {
                val rootWidth = rootRelativeLayout.measuredWidth
                val rootHeight = rootRelativeLayout.measuredHeight
                val minLine = Math.max(rootWidth, rootHeight)
                val tvUnread = TextView(rootRelativeLayout.context)
                tvUnread.id = INTEGER_ID_TV_UNREAD + KEY_ID
                rootRelativeLayout.addView(tvUnread)
                val tvUnReadParams = tvUnread.layoutParams as RelativeLayout.LayoutParams
                tvUnReadParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
                tvUnReadParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
                tvUnReadParams.marginEnd = minLine / 8
                tvUnReadParams.width = minLine / 5
                tvUnReadParams.height = minLine / 5
                tvUnread.layoutParams = tvUnReadParams
                tvUnread.setBackgroundColor(Color.RED)
                tvUnread.isSingleLine = true
                tvUnread.visibility = View.INVISIBLE
                tvUnread.gravity = Gravity.CENTER
            }, 20)


            //add listener
            initParentClickEvent(parentLinear, parentCounter)
            parentCounter++

            //add content view--imageview and textview
            parentLinear.postDelayed(Runnable {
                val ivImg = NavBottomAnimImageVIew(parentLinear.context)
                val tvName = NavBottomAnimTextVIew(parentLinear.context)
                ivImg.id = INTEGER_ID_IV_IMG + KEY_ID
                tvName.id = INTEGER_ID_TV_NAME + KEY_ID
                parentLinear.addView(ivImg)
                parentLinear.addView(tvName)
                //初始化宽高
                val ivWH = dip2px(it.imgWH)
                val ivImgParams = ivImg.layoutParams as LinearLayout.LayoutParams
                ivImgParams.height = ivWH
                ivImgParams.width = ivWH
                ivImg.layoutParams = ivImgParams

                val tvImgParams = tvName.layoutParams as LinearLayout.LayoutParams
                tvImgParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
                tvImgParams.topMargin = dip2px(it.interval)
                tvName.layoutParams = tvImgParams
                tvName.gravity = Gravity.CENTER
                tvName.textSize = it.nameTxSize

                //初始化信息
                if (it.imgSel?.isRecycled == false) {
                    ivImg.setImageBitmap(it.imgUnSel)
                }
                tvName.text = it.nameUnSel ?: ""
                tvName.setTextColor(it.nameUnSelColor)

                ivImg.visibility = if(it.imgSwitch) View.VISIBLE else View.GONE
                tvName.visibility = if(it.txtSwitch) View.VISIBLE else View.GONE

                if (childCounter == uiInfoList.size - 1) {
                    //最后一个--初始化第一个为选中
                    mSelPosition.set(-1)
                    setSelWithPosition(0)
                }
                childCounter++
            }, 20)
        }
    }


    //外部实现---------------------------------------------------------------------------------------

    override fun initUI(uiInfoList: MutableList<NavBottomUIInfo>?) {
        innerInitUI(uiInfoList)
    }

    /**
     * 设置选中,0开始
     * */
    override fun setSelWithPosition(position: Int) {
        innerSetSelWithPosition(position, true)
    }

    /**
     * 设置选中位置：传入对象的identify
     * */
    override fun setSelWithIdentify(identify: Int) {
        //获取数据集合中的identify位置，再走回传入位置参数逻辑
        val queryPos = queryPosWithIdentify(identify)
        if (queryPos == -1) {
            return
        }
        setSelWithIdentify(queryPos)
    }


    /**
     * 设置与viewpager关联
     * */
    override fun setupWithViewPager(vp: ViewPager?) {
        if (vp == null) {
            return
        }
        mRelViewPager = vp
        mRelViewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                //同时更新按钮UI
                innerSetSelWithPosition(position, false)
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
    }

    /**
     * tab数量
     * */
    override fun getTabCount(): Int {
        return mUIParentList.size
    }

    /**
     * 清空所有tab
     * */
    override fun removeAllTab() {
        mUIParentList.clear()
        mUiInfoList.clear()
        mSelPosition.set(-1)
        removeAllViews()
    }


    /**
     * 获取当前选中位置
     * */
    override fun getCurrentPosition(): Int {
        return mSelPosition.get()
    }


    /**
     * 是否显示图片点击动画
     * */
    override fun clickImgAnim(show: Boolean) {
        this.mAnimImgSwitch = show
    }


    /**
     * 是否显示文字点击动画
     * */
    override fun clickTxtAnim(show: Boolean) {
        this.mAnimTxtSwitch = show
    }


    /**
     * 设置某个位置下的未读数
     * */
    override fun setUnreadWithPosition(position: Int, info: NavBottomUnreadInfo) {
        val totalCount = getTabCount()
        if (totalCount - 1 <= position || totalCount <= 0) {
            return
        }
        val rootLayout = mUIParentList.get(position)
        val uiInfo = mUiInfoList.get(position)
        val KEY_ID = uiInfo.identify
        rootLayout.postDelayed(Runnable {
            //INTEGER_ID_TV_UNREAD + KEY_ID
            var unreadView = rootLayout.findViewById<TextView>(INTEGER_ID_TV_UNREAD + KEY_ID)
            unreadView?.text = ""
            if (info.msgCount <= 0) {
                unreadView?.visibility = View.INVISIBLE
                return@Runnable
            }
            unreadView?.visibility = View.VISIBLE
            when (info.msgType) {
                NavBottomUnreadInfo.MESSAGE_TYPE.NUMBER -> {
                    unreadView?.setTextColor(info.msgTxColor)
                    unreadView?.textSize = info.msgTxSize
                    unreadView?.text = info.msgCount.toString()

                    unreadView?.setBackgroundResource(info.msgBgColor)
                }
                NavBottomUnreadInfo.MESSAGE_TYPE.POINT -> {

                    unreadView?.setBackgroundResource(info.msgBgColor)
                }
            }
        }, 300)
    }

    /**
     * 设置某个identify的未读数
     * */
    override fun setUnReadWithIdentify(identify: Int, info: NavBottomUnreadInfo) {
        //获取数据集合中的identify位置，再走回传入位置参数逻辑
        val queryPos = queryPosWithIdentify(identify)
        if (queryPos == -1) {
            return
        }
        setSelWithIdentify(queryPos)
    }

    /**
     * 清空某个位置下的未读数
     * */
    override fun clearUnreadWithPosition(position: Int) {
        setUnreadWithPosition(position, NavBottomUnreadInfo())
    }

    /**
     * 清空某个identify下的未读数
     * */
    override fun clearUnreadWithIdentify(identify: Int) {
        val queryPos = queryPosWithIdentify(identify)
        if (queryPos == -1) {
            return
        }
        clearUnreadWithPosition(queryPos)
    }


    /**
     * 设置全部为已读
     * */
    override fun readAll() {
        for (i in 0 until mUiInfoList.size) {
            clearUnreadWithPosition(i)
        }
    }


    override fun onDetachedFromWindow() {
        removeOnTabSelectListener()
        super.onDetachedFromWindow()
    }

    override fun setOnTabSelectListener(listener: NavBottomOnTabSelectListener) {
        this.mListener = listener
    }

    override fun removeOnTabSelectListener() {
        this.mListener = null
    }
}